package cc.git.liuyan.customeraiagent.core.provider.giteeai.api.interceptor;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;

public class ApiKeyHeaderInterceptor implements Interceptor {

    private final Map<String, String> headers = new HashMap<>();

    public ApiKeyHeaderInterceptor(String apiKey) {
        Optional.ofNullable(apiKey).ifPresent(new Consumer<String>() {
            @Override
            public void accept(String apiKey) {
                headers.put("Authorization", "Bearer " + apiKey);
            }
        });
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        // Add headers
        this.headers.forEach(builder::addHeader);
        return chain.proceed(builder.build());
    }
}
